package manage.action;

import com.alibaba.fastjson.JSONObject;
import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.service.HostInfoService;
import m.system.RuntimeData;
import m.system.cache.*;
import m.system.exception.MException;
import m.system.url.UrlMarker;
import m.system.util.HttpRequestUtil;
import m.system.util.JSONMessage;
import m.system.util.StringUtil;
import manage.util.DictionaryUtil;

import java.util.HashMap;
import java.util.Map;

@ActionMeta(name="manage/hostInfo")
public class HostInfoAction extends ManageAction {
	@RequestMeta(params= {"ipport","method","fieldOid","param"})
	public JSONMessage operHost(String ipport,String method,String fieldOid,String param) throws Exception {
		verifyAdminOperPower("manage_system_power");
		new Thread(() -> {
			try {
				RuntimeData.getService(HostInfoService.class).operHost(ipport,method,fieldOid,param);
			} catch (MException e) {
				e.printStackTrace();
			}
		}).start();
		return new JSONMessage(0,"请求已发送");
	}
	public JSONMessage toList() throws Exception {
		verifyAdminOperPower("manage_system_power");
		return new JSONMessage(0)
				.push("list", getService(HostInfoService.class).getList())
				.push("host", HostInfoService.getCurrentHost());
	}
	@RequestMeta(params= {"urlHost"})
	public JSONMessage getCacheList(String urlHost) throws Exception {
		JSONMessage message=new JSONMessage(0);
		verifyAdminOperPower("manage_system_power");
		if(!StringUtil.isSpace(urlHost)) {
			Map<String,String> header= new HashMap<>();
			header.put("Authorization", UrlMarker.getAuth()+" "+getSessionAdmin().getToken());
			JSONObject json=JSONObject.parseObject(new HttpRequestUtil().doPost("http://"+urlHost+actionUrl("getCacheList"), "", header));
			message.push("model",json.get("model"));
			message.push("cacheHost",json.get("cacheHost"));
			message.push("cacheMap",json.get("cacheMap"));
			message.push("cacheMap2",json.get("cacheMap2"));
			message.push("cacheList",json.get("cacheList"));
		}else {
			message.push("model", HostInfoService.getCurrentHost());
			message.push("cacheHost", CacheHost.getAll());
			message.push("cacheMap", CacheMap.getAll());
			message.push("cacheMap2", CacheMap2.getAll());
			message.push("cacheList", CacheMapList.getAll());
		}
		return message;
	}
	@RequestMeta(params= {"urlHost"})
	public JSONMessage clearCache(String urlHost) throws Exception {
		verifyAdminOperPower("manage_system_power");
		if(!StringUtil.isSpace(urlHost)) {
			Map<String,String> header= new HashMap<>();
			header.put("Authorization", UrlMarker.getAuth()+" "+getSessionAdmin().getToken());
			new HttpRequestUtil().doPost("http://"+urlHost+actionUrl("clearCache"), "", header);
		}else{
			CacheUtil.clearAll();
			DictionaryUtil.clearAll(false);
		}
		return new JSONMessage(0,"操作成功");
	}
	

}
